package com.itheima.mobile;

import cn.hutool.core.date.DateUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.itheima.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * @description:
 * @author: dalao
 * @date: 2020/4/15-19:48
 * @Version: 1.0.0
 */
@RestController
@RequestMapping("/pay")
public class AlipayController {
    @Reference
    private OrderService orderService;
//    支付宝服务器地址
    private String serverUrl =  "https://openapi.alipaydev.com/gateway.do";
//    APP_ID
    private String APP_ID="2016102100733808";
//    私钥
    private String APP_PRIVATE_KEY="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCSKkf8reyVtOHxBNL6fhV1+WmyHPwjnIKVcPfDL6KwlggsaVampf5msAYe4YgCEozTdiarW+SwKHf26A9g7laJkxF4H3RD+KKmtupZTM3+KAoWCwkRicnB0X9SCMKFHYG0V5CnX2quTEQIp+RrMrEFdvzUX1Gam4BinCh4aQ3I40GZ8EQHlVWMv7bRJzMIoRBb0kPIL+Dmy6SqoG9Q5gLaXPRe3aPaAntJkWdo6wft3642KNV4Wr92vnAH9idc4aYHsoNxr23nzQ5kDoO6RBspxciIj/EZbUuiA3n94HkxjSTp7hy+S8imkHnQ3yrYbsxq9uofFgU/L0j942M7+peXAgMBAAECggEARDgvuSOEFKuD+PYDcp5+bb2nM1aL6CMYX5+GRDdre3fLAM95ffZjspHdiXRCApWd3OR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M03O9DA3tMOV214XfijVaGAG9osWghYCjE+XYqI6aYANJ/2LP2lud3LaYfy+oK267M6U=";
//    编码
    private String CHARSET = "UTF-8";
//    公钥
    private String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAljCwMTYwzE8L9s4g3UkGTvEiSn8KCOUIILRnSkXquvzkM50637uoDQZyIZCWlDGQiVQa0ciPCoc+L2f8me6iQERtwpBPEkPmePF0LfWkX1Yevcjr99laQ0Io9Yl9xh26ldL1g4DmruRkBtVdh0fdrL6JfaXrO9G/Y9dnzXbWuCKXXbct1isbySpqYKr2OpV4usjKTVxxM48ZrnLBaytFLkwC/ejl6rw1Mw6T3wTfzzqClJfkrUbgl6dcIbjGNdVAomW4FdHIadW+ZeyTHdVcm3+AcW1O/H4IGccnE2Tl1L7cwNnqn8nw74hMBCGTeG3DgF0OGePMunyQu2qt87ttuwIDAQAB";

    @RequestMapping("/alipay")
    public void alipay(HttpServletRequest httpRequest,
                       HttpServletResponse httpResponse,Integer orderId) throws ServletException, IOException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                    serverUrl,
                    APP_ID, APP_PRIVATE_KEY, "json",
                    CHARSET, ALIPAY_PUBLIC_KEY, "RSA2");
        //创建API对应的request
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        //在公共参数中设置回跳和通知地址
//        支付成功跳转地址
        alipayRequest.setReturnUrl("http://teym5s.natappfree.cc/pages/orderSuccess.html?orderId="+orderId);
//        支付成功通知地址
        alipayRequest.setNotifyUrl("http://teym5s.natappfree.cc/pay/alipayNotify.do");
//        查询预约信息
        Map order = orderService.findById(orderId);
//        创建json
        JSONObject json = new JSONObject();
//        订单号 , 不重复
        String outTradeNo = outTradeNo(orderId);
//        更新订单号 , 支付状态
        orderService.updateOutTradeNo(orderId,outTradeNo);
        json.put("out_trade_no",outTradeNo);
        json.put("product_code","QUICK_WAP_PAY");
//        价格
        json.put("total_amount",2888);
        json.put("subject",order.get("setmeal"));
        alipayRequest.setBizContent(json.toJSONString());//填充业务参数
        String form="";
        try {
            //调用SDK生成表单
            form = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    private String outTradeNo(Integer orderId){
        String datestr = DateUtil.format(new Date(),"yyyyMMddHHmmss");
        return datestr+orderId;
    }
    Logger log = LoggerFactory.getLogger(AlipayController.class);
    /**
     * 支付宝通知我们支付状态，在这个接口里面可以修改订单支付的状态
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/alipayNotify")
    @ResponseBody
    public String alipayNotify(HttpServletRequest request, HttpServletRequest response) throws Exception {

        log.info("支付成功, 进入异步通知接口...");

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2"); //调用SDK验证签名
        //——请在这里编写您的程序（以下代码仅作参考）——
		/* 实际验证过程建议商户务必添加以下校验：
		1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
		2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
		3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
		4、验证app_id是否为该商户本身。
		*/
        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意： 尚自习的订单没有退款功能, 这个条件判断是进不来的, 所以此处不必写代码
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if (trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知

                // 修改叮当状态，改为 支付成功，已付款; 同时新增支付流水
                orderService.updatePayStatus(out_trade_no);
            }
            log.info("支付成功...");
        }else {//验证失败
            log.info("支付, 验签失败...");
        }

        return "success";
    }
}
